<template>
  <section>
    <iframe src="" frameborder="0" width="0" height="0" id="paiziID"></iframe>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <span>状态：</span>
          <el-radio-group v-model="selectItem.type" @change="currentChange">
            <el-radio-button v-for="(item, index) in typeMaps" :label="item.value" name="status" :key="index">{{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="success" v-on:click="addField" v-if="!syncButton || !sureCheckButton || topPuriew">新增</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="warning" style="width: 120px" @click="onekeySync" v-if="syncButton">一键同步</el-button>
        </el-form-item>
        <div style="display: inline-block;float: right">
          <el-form :inline="true">
            <el-select v-model="selectItem.query" placeholder="请选择" @change="currentSelChange">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-form-item>
              <el-input :placeholder="selectItem.query" v-model="selectItem.keywords" v-if="selectItem.query != 'area_name'" @keyup.enter.native="doSearch"></el-input>
              <select v-model="selectItem.keywords" style="width: 170px;height: 35px;border-radius: 5px;font-size: 18px;" @change="doSearch" v-else>
                <option :value="item" v-for="(item, index) in areaName">{{ item }}</option>
              </select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="doSearch">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="background: #13ce66" v-on:click="_reload">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="readyFieldsData" border style="width: 100%" v-loading="loading" element-loading-text="玩命请求中。。。">
      <el-table-column prop="id" label="id" width="80">
      </el-table-column>
      <el-table-column prop="farm_id" label="农场" width="100" :formatter="farmName">
      </el-table-column>
      <el-table-column prop="area_name" label="区名" width="100">
      </el-table-column>
      <el-table-column prop="name" label="地名" width="100">
      </el-table-column>
      <el-table-column prop="work_name" label="姓名" width="100">
      </el-table-column>
      <el-table-column label="种植信息" width="240">
        <template slot-scope="scope">
          <div v-if="scope.row.plant_name">
            <div class="field_list_left">
              <img :src="scope.row.list_pic" alt="">
            </div>
            <div class="field_list_right">
              <p>{{ scope.row.plant_name }}</p>
            </div>
          </div>
          <span v-else>暂未种植</span>
        </template>
      </el-table-column>
      <el-table-column prop="plant_time" label="种植时间">
      </el-table-column>
      <el-table-column prop="collect_time" label="预熟时间" :formatter="collectTime">
      </el-table-column>
      <el-table-column prop="status" label="地块状态" width="140" :formatter="changeStatus">
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <div style="margin-left: 5px;">
            <el-button type="default" size="small" @click="builPaizi(scope.row)" >打印牌子</el-button>
            <template v-if="sureCheckButton">
              <el-button type="success" size="small" @click="sureCheck(scope.row.id, 3)" v-if="scope.row.status === '1'">确认审核</el-button>
            </template>
            <!--超级管理员或者农场运营拥有权限-->
            <template v-if="!syncButton || !sureCheckButton || topPuriew">
              <el-button type="warning" size="small" @click="submitToCheck(scope.row.id, 1, '')" v-if="scope.row.status === '0'">提交审核</el-button>
              <el-button type="info" size="small" @click="submitToCheck(scope.row.id, 2, '')" v-if="scope.row.status === '1' || scope.row.status === '2'">撤销提交</el-button>
              <el-button type="danger" size="small" @click="deleteReadyField(scope.row.id)" v-if="scope.row.status === '0'">删除</el-button>
              <el-button type="primary" size="small" @click="editField(scope.row)" v-if="scope.row.status === '0'">编辑</el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--删除菜品选择原因弹窗-->
    <el-dialog title="删除地块" :visible.sync="deleteDialogVisible" size="tiny">
      <span>删除原因:</span>
      <template>
        <p><el-radio class="radio" v-model="number" label="0">种错位置了</el-radio></p>
        <p><el-radio class="radio" v-model="number" label="1">菜品发育不良</el-radio></p>
        <p><el-radio class="radio" v-model="number" label="2">无法存活死亡</el-radio></p>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!--确认审核提示弹窗-->
    <el-dialog title="确认审核" :visible.sync="sureCheckDialogVisible" size="tiny">
      <span style="color: red;">请慎重审核后，选择相应的按钮！！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="sendCheckCommond('yes')">通过审核</el-button>
        <el-button type="warning" @click="sendCheckCommond('no')">否定审核</el-button>
        <el-button @click="sureCheckDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!--新增新一期菜品-->
    <el-dialog title="新增菜品" v-model="addFieldShow" :close-on-click-modal="false">
      <el-form :model="addFieldForm" label-width="80px" ref="addForm">

        <el-form-item label="选择菜地" prop="plant_name">
          <template slot-scope="scope">
            <el-cascader :options="caderAreaName" @active-item-change="mapItemChange" :props="props" v-model="addFieldForm.map_info"></el-cascader>
          </template>
        </el-form-item>

        <el-form-item label="蔬菜名" prop="plant_name">
          <template slot-scope="scope">
            <el-select v-model="addFieldForm.plant_name" placeholder="请选择">
              <el-option
                v-for="(item, index) in plants"
                :key="index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="种植时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="addFieldForm.plant_time" type="date" placeholder="选择日期"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-31</span>
          </template>
        </el-form-item>

        <el-form-item label="预熟时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="addFieldForm.collect_time" type="date" placeholder="选择日期" :picker-options="pickerPtions"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-21</span>
          </template>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFieldShow = false">取消</el-button>
        <el-button type="primary" @click.native="setNewField(1)" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--编辑菜品-->
    <el-dialog title="编辑菜品" v-model="editFieldShow" :close-on-click-modal="false">
      <el-form :model="addFieldForm" label-width="80px" ref="addForm">
        <el-form-item label="预熟时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="addFieldForm.collect_time" type="date" placeholder="选择日期" :picker-options="pickerPtions"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-21</span>
          </template>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFieldShow = false">取消</el-button>
        <el-button type="primary" @click.native="setNewField(2)" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--分页-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        @current-change="currentPageChange"
        :page-size="30"
        layout="prev, pager, next, jumper"
        :total="total" style="float:right;" :current-page="parseInt(selectItem.page)">
      </el-pagination>
      <span style="float: right;margin-top: 6px;margin-right: 5px">共 {{total}} 条数据</span>
    </el-col>

  </section>
</template>

<script type="text/ecmascript-6">
  import util from '../../util'
  import NProgress from 'nprogress'
  import { isUrlHasPurview } from '../../vuex/getters'
  import { apiTree } from '../../apiTree'

  export default {
    name: 'readyPlant',
    // 局部注册组件
    data() {
      return {
        typeMaps: [
          {value: -1, label: '全部'},
          {value: 0, label: '待提交'},
          {value: 1, label: '待审核'},
          {value: 2, label: '未过审'},
          {value: 3, label: '待上线'},
          {value: 4, label: '已上线'}
        ],
        options: [
          {value: 'area_name', label: '区域名'},
          {value: 'plant_name', label: '菜品'}
        ],
        reason: ['种错位置了', '菜品发育不良', '无法存活死亡'],
        commondId: 0,
        props: {
          value: 'label',
          children: 'names'
        },
        loading: false,
        areaName: [],
        number: '0',
        caderAreaName: [], // 连级选择器使用选项
        addFieldShow: false,
        editFieldShow: false, // 编辑菜品弹窗
        deleteDialogVisible: false, // 删除弹框
        sureCheckDialogVisible: false, // 删除弹框
        addLoading: false,
        addFieldForm: {
          id: 0,
          map_info: [],
          plant_name: '',
          plant_time: '',
          collect_time: ''
        },
        orginAddFieldForm: {},
        maturity: 0, // 成熟期
        plants: [],
        readyFieldsData: [], // 列表数据
        total: 0,
        selectItem: {
          page: this.$route.query.page !== undefined ? this.$route.query.page : 1,
          query: this.$route.query.query !== undefined ? this.$route.query.query : '',
          keywords: this.$route.query.keywords !== undefined ? this.$route.query.keywords : '',
          type: this.$route.query.type !== undefined ? this.$route.query.type : -1
        }
      }
    },
    methods: {
      // 打印牌子
      builPaizi(row) {
        document.getElementById('paiziID').src = '/index.php?c=other&a=buildPaizi&params=' + encodeURIComponent(JSON.stringify({
            farm_id: row.farm_id,
            map_id: row.map_id,
            title: row.area_name + row.name,
            plant_name: row.plant_name,
            plant_time: util.formatDate.format(new Date(row.plant_time), 'yyyy年MM月dd日'),
            collect_time: util.formatDate.format(new Date(row.collect_time * 1000), 'yyyy年MM月dd日')
          }));
      },
      // 农场名称
      farmName(row, column) {
        return row.farm_id === '1' ? '枫泾' : '其他农场'
      },
      // 预熟时间
      collectTime(row, column) {
        return row.collect_time === 0 ? 0 : util.formatDate.format(new Date(row.collect_time * 1000), 'yyyy-MM-dd')
      },
      // 对应状态显示
      changeStatus(row) {
        if (row.status === '0') {
          return '待提交';
        } else if (row.status === '1') {
          return '待审核';
        } else if (row.status === '2') {
          return '未过审';
        } else if (row.status === '3') {
          return '待上线';
        } else if (row.status === '4') {
          return '已上线';
        }
      },
      // 选项卡选择
      currentChange() {
        this.$router.push({path: this.$route.path, query: this.selectItem})
      },
      // 选择时间
      pickerPtions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      // 选择页码
      currentPageChange(val) {
        this.selectItem.page = val
        this.$router.push({path: this.$route.path, query: this.selectItem})
      },
      // 下拉框变化
      currentSelChange() {
        if (this.selectItem.query === 'area_name') {
          this.showAreaNmae = true
          this.getAreaName()
        } else {
          this.selectItem.keywords = ''
          this.showAreaNmae = false
        }
      },
      // 搜索
      doSearch() {
        if (this.selectItem.query === 'area_name' && util.isEmpty(this.selectItem.keywords)) {
          return;
        }
        if (this.selectItem.query) {
          this.$router.push({path: this.$route.path, query: this.selectItem})
        }
      },
      // 刷新页面
      _reload() {
        alert('稍等....');
      },
      // 获得区域名
      getAreaName() {
        this.areaName = [];
        apiTree('readyPlant/index', 'field/getAreaName', {type: 1}).then((res) => {
          if (res.s === 1) {
            res.d.data.forEach((item) => {
              this.areaName.push(item.area_name);
              this.caderAreaName.push({'label': item.area_name, 'names': []});
            })
          }
        })
      },
      // 获得植物名
      getPlantName() {
        this.plants = []
        apiTree('readyPlant/index', 'field/getAllPlantName', {}).then((res) => {
          if (res.s === 1) {
            res.d.data.forEach((item) => {
              this.plants.push(item.name);
            });
          }
        })
      },
      // 获得预种植的菜地列表
      getReadyPlantMapList() {
        let param = this.$route.query
        if (util.isEmptyObject(param)) {
          this.selectOptions = {
            page: 1,
            query: '',
            keywords: '',
            type: -1
          }
        }
        NProgress.start()
        this.loading = true;
        apiTree('readyPlant/index', 'field/getReadyPlantMapList', param).then((res) => {
          if (res.s === 1) {
            this.readyFieldsData = res.d.data;
            this.total = res.d.total_num;
            NProgress.done();
            this.loading = false;
          }
        })
      },
      // 新增预种植菜品
      addField() {
        this.addFieldShow = true;
      },
      // 编辑预种地地块
      editField(row) {
        this.editFieldShow = true;
        this.addFieldForm = {
          id: row.id,
          map_info: [row.area_name, row.name],
          plant_name: row.plant_name,
          plant_time: row.plant_time,
          collect_time: util.formatDate.format(new Date(row.collect_time * 1000), 'yyyy-MM-dd')
        }
      },
      mapItemChange(_val) {
        apiTree('readyPlant/index', 'field/getSingleAreaName', {area_name: _val[0]}).then((res) => {
          if (res.s === 1) {
            this.caderAreaName[util.itemPos(this.areaName, _val[0])].names = [];
            // 将数据填加到二级子菜单中
            res.d.data.forEach((item, index) => {
              this.caderAreaName[util.itemPos(this.areaName, _val[0])].names.push({'label': item.name});
            })
          }
        })
      },
      // 新增种植信息
      setNewField(_commond) {
        if (!this.addFieldForm.plant_time && _commond === 1) {
          this.$message.error('种植时间为空！');
          return;
        }
        if (!this.addFieldForm.collect_time) {
          this.$message.error('预熟时间为空！');
          return;
        }
        if (util.isEmpty(this.addFieldForm.map_info && _commond === 1)) {
          this.$message.error('未选择菜地！');
          return;
        }
        if (util.isEmpty(this.addFieldForm.plant_name && _commond === 1)) {
          this.$message.error('未选择植物！');
          return;
        }
        let plant_time = parseInt(new Date(this.addFieldForm.plant_time).getTime()) / 1000;
        let collect_time = parseInt(new Date(this.addFieldForm.collect_time).getTime()) / 1000;
        let param = {
          id: this.addFieldForm.id,
          map_info: this.addFieldForm.map_info,
          plant_name: this.addFieldForm.plant_name,
          plant_time: plant_time,
          collect_time: collect_time
        }
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          apiTree('readyPlant/index', 'field/setReadyField', {'data': param}, 'POST').then((res) => {
            if (res.s === 1) {
              this.$message({
                message: '命令执行成功',
                type: 'success'
              });
              this.addFieldShow = false;
              this.editFieldShow = false;
              this.addFieldForm = this.orginAddFieldForm;
              this.getReadyPlantMapList();
            } else {
              this.$message.error(res.err_str)
            }
          })
        })
      },
      // 提交审核
      submitToCheck(_id, _type, _desc) {
        apiTree('readyPlant/index', 'field/checkReadyPlantStatus', {type: _type, id: _id, desc: _desc}).then((res) => {
          if (res.s === 1) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            // 关闭删除弹窗
            if (_type === 4) {
              this.deleteDialogVisible = false;
            }
            // 关闭确认审核弹框
            if (_type === 3) {
              this.sureCheckDialogVisible = false;
            }
            this.getReadyPlantMapList();
          } else {
            this.$message.error(res.err_str)
          }
        });
      },
      // 确认审核
      sureCheck(_id, _type) {
        this.sureCheckDialogVisible = true;
        this.commondId = _id;
      },
      // 通过审核，或者未通过审核
      sendCheckCommond(_commond) {
        this.submitToCheck(this.commondId, 3, _commond);
      },
      // 删除预种植地块
      deleteReadyField(_id) {
        this.number = '0';
        this.deleteDialogVisible = true;
        this.commondId = _id;
      },
      // 删除提交原因
      deleteSubmit() {
        let _reason = this.reason[this.number];
        if (util.isEmpty(_reason)) {
          this.$message.error('未选择删除原因！')
          return
        }
        this.submitToCheck(this.commondId, 4, _reason);
      },
      // 一键同步
      onekeySync() {
        this.$confirm('是否将所有待上线的菜品进行同步！' , '很重要的提示', {
          confirmButtonText: '我已经核对好了，确定同步',
          cancelButtonText: '我还要再核对一遍',
          type: 'warning'
        }).then(() => {
          apiTree('readyPlant/sync', 'field/onekeySync', {}).then((res) => {
            if (res.s === 1) {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.getReadyPlantMapList();
            } else {
              this.$message({
                type: 'info',
                message: '有未同步成功的数据，请联系管理员。。。'
              });
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '请谨慎操作。。。'
          });
        })
      }
    },
    computed: {
      // 一键同步菜品
      syncButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'readyPlant/sync'))
      },
      // 确认审核
      sureCheckButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'readyPlant/check'))
      },
      topPuriew() {
        return this.$store.state.adminer.om_uid === 999
      }
    },
    created() {
      this.getAreaName();
      this.getPlantName();
      this.getReadyPlantMapList();
      // 克隆一份最原始数据
      this.orginAddFieldForm = util.cloneObj(this.addFieldForm);
    },
    watch: {
      $route: 'getReadyPlantMapList'
    }
  }

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .field_list_left
    display inline-block
    vertical-align middle
    margin-top 5px
    & img
      width 110px
      height 60px
  .field_list_right
    display inline-block
    vertical-align middle
    margin-left 5px
</style>